﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using System.Data.Services.Client;

using WebRole1.DataService;
using WindowsLive;

namespace WebRole1
{
   class Utils
   {
      const string LoginCookie = "webauthtoken";
      static WindowsLiveLogin wll = new WindowsLiveLogin(true);
      public static string AppId = wll.AppId;

      public static string GetUserFromCookie()
      {
         HttpRequest req = HttpContext.Current.Request;
         HttpCookie loginCookie = req.Cookies[LoginCookie];

         if (loginCookie == null)
         {
            return null;
         }
         string token = loginCookie.Value;

         if (!string.IsNullOrEmpty(token))
         {
            WindowsLiveLogin.User user = wll.ProcessToken(token);
            if (user != null)
            {
               return user.Id;
            }
         }
         return null;
      }

      public static UserTbl GetCurrentUser(LocationsDBEntities locEntities, string userId)
      {
         if (string.IsNullOrEmpty(userId))
         {
            throw new Exception("Live user cannot be empty");
         }

         int userCnt = locEntities.UserTbl.Count(f => f.LiveIDGuid == userId);
         if (userCnt == 0)
         {
            UserTbl newUser = new UserTbl();
            newUser.LiveIDGuid = userId;
            newUser.LastLoginDate = DateTime.Now.ToUniversalTime();
            newUser.FirstLoginDate = DateTime.Now.ToUniversalTime();
            newUser.UserName = userId;
            
            locEntities.AddToUserTbl(newUser);
            locEntities.SaveChanges();
         }

         var user = locEntities.UserTbl.First(f => f.LiveIDGuid == userId);

         return user;
      }

   }
}